package controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

public class UploadContr extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public UploadContr() {
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HashMap<String, String> temp = processOneUpload(request, "C:/etc", "test");
		for (Entry<String, String> e : temp.entrySet()) {
			System.out.println(e.getKey() + ": " + e.getValue());
		}
	}

	@SuppressWarnings("unchecked")
	public static HashMap<String, String> processOneUpload(
			HttpServletRequest request, String path, String newFileBaseName)
			throws ServletException, IOException {
		HashMap<String, String> formFields = new HashMap<String, String>();
		try {
			List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
					String fieldName = item.getFieldName();
					String fieldValue = item.getString();
					formFields.put(fieldName, fieldValue);
				} else {
					// Process form file field (input type="file").
					String fieldName = item.getFieldName();
					String fileExt = FilenameUtils.getExtension(item.getName());

					// Tao file luu
					File dFile = new File(path);
					dFile.mkdirs();
					File file = new File(dFile, newFileBaseName + "." + fileExt);
					if (!file.exists())
						file.createNewFile();

					// Doc va luu file
					BufferedInputStream bis = new BufferedInputStream(item.getInputStream());
					BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));

					int read = 0;
					byte[] bytes = new byte[1024];

					while ((read = bis.read(bytes)) != -1) {
						bos.write(bytes, 0, read);
					}

					bis.close();
					bos.flush();
					bos.close();
					formFields.put(fieldName, file.getAbsolutePath());
				}
			}
		} catch (FileUploadException e) {
			throw new ServletException("Cannot parse multipart request.", e);
		}

		return formFields;
	}

	@SuppressWarnings("unchecked")
	public static HashMap<String, String> processOneUploadByID( HttpServletRequest request, String path) throws ServletException, IOException {
		HashMap<String, String> formFields = new HashMap<String, String>();
		FileItem fileItem = null;
		try {
			List<FileItem> items = new ServletFileUpload( new DiskFileItemFactory()).parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
					String fieldName = item.getFieldName();
					String fieldValue = item.getString();
					formFields.put(fieldName, fieldValue);
				} else {
					// Process form file field (input type="file").
					fileItem = item;
				}
			}
			
			String fileField = fileItem.getFieldName();
			String fileExt = FilenameUtils.getExtension(fileItem.getName());
			
			// Bat dau luu file (vi chi co 1 file dc up nen vong lap file chi
			// chay 1 lan, neu co nhieu file -> file cuoi cung)
			// Tao file luu
			File dFile = new File(path);
			dFile.mkdirs();
			File file = new File(dFile, formFields.get("id") + "." + fileExt);
			if (!file.exists())
				file.createNewFile();

			// Doc va luu file
			BufferedInputStream bis = new BufferedInputStream( fileItem.getInputStream());
			BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(file));

			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = bis.read(bytes)) != -1) {
				bos.write(bytes, 0, read);
			}

			bis.close();
			bos.flush();
			bos.close();
			formFields.put(fileField, file.getAbsolutePath());
		} catch (FileUploadException e) {
			throw new ServletException("Cannot parse multipart request.", e);
		} catch (NullPointerException e) {
			throw new ServletException("No file found.", e);
		}

		return formFields;
	}
	
	public static void deleteFile(String path){
		File file = new File(path);
		if(file.exists() && file.isFile()) {
			file.delete();
		}
	}
}
